package cn.bincker.mycaptcha.letter;

import cn.bincker.mycaptcha.CaptchaVerifier;
import cn.bincker.mycaptcha.VerifyRequestAnswerResolver;
import cn.bincker.mycaptcha.basic.AnswerStorage;
import cn.bincker.mycaptcha.basic.exception.CaptchaExpireException;
import cn.bincker.mycaptcha.basic.exception.CaptchaVerifyFailException;
import cn.bincker.mycaptcha.letter.entity.LetterAnswer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LetterCaptchaVerifier implements CaptchaVerifier {
    private final VerifyRequestAnswerResolver<LetterAnswer> answerResolver;
    private final AnswerStorage<LetterAnswer> answerStorage;

    public LetterCaptchaVerifier(VerifyRequestAnswerResolver<LetterAnswer> answerResolver, AnswerStorage<LetterAnswer> answerStorage) {
        this.answerResolver = answerResolver;
        this.answerStorage = answerStorage;
    }

    @Override
    public void verify(HttpServletRequest request, HttpServletResponse response) {
        var answer = answerStorage.getAndRemove(request).orElseThrow(CaptchaExpireException::new).getCode();
        if(!answerResolver.resolver(request).getCode().equals(answer)){
            throw new CaptchaVerifyFailException();
        }
    }
}
